import {Service, action} from "adajs";

class AccordionService extends Service {
    defaultData() {
        return {
            isError: false,
            sorts: []
        };
    }

    onupdate(current, data) {
        return this.context.request.post("/api/lgb/app/lgb/telephone/queryPage", {lbDm: 0}).then(({data}) => {
            if (data) {
                let list = data.rows, sorts = [];
                list.forEach(item => {
                    let sort = sorts.find(sort => sort.xh === item.xh);
                    if (!sort) {
                        sort = {
                            xh: item.xh,
                            name: item.lbDm,
                            origin: [],
                            list: [],
                            open: false
                        };
                        sorts.push(sort);
                    }
                    sort.origin.push(item);
                    sort.list.push(item);
                });
                current.sorts = sorts;
                if (current.sorts[0]) {
                    current.sorts[0].open = true;
                }
            } else {
                current.isError = true;
            }
        });
    }

    @action("toggle")
    toggle(current, sort) {
        let target = current.sorts.find(_sort => _sort.xh === sort.xh);
        if (target) {
            target.open = !target.open;
        }
    }

    @action("search")
    search(current, keyword) {
        current.sorts.forEach(sort => {
            let result = sort.origin.filter(item => keyword === "" || item.mc.indexOf(keyword) !== -1);
            sort.list = result;
        });
    }
}

export default AccordionService;